//
//  LSZComposeViewController.swift
//  醒浪微博
//
//  Created by 雷顺哲 on 16/7/18.
//  Copyright © 2016年 LSZ. All rights reserved.
//

import UIKit
import SVProgressHUD

class LSZComposeViewController: UIViewController {
    
    // MARK: 懒加载控件
//    中间的顶部label
    private lazy var titleLabel: UILabel = {
        let label =  UILabel(textColor: UIColor.grayColor(), fontSize: 17)
        
        label.numberOfLines = 0
        label.textAlignment = .Center

//        获取用户名
        if let name = LSZUserAccountViewModel.sharedUserAccount.userAccount?.name {
            
            let title = "发微博\n\(name)"
//            添加到富文本
            let attributeStr = NSMutableAttributedString(string: title)
//            获取名字的范围
            let range = (title as NSString).rangeOfString(name)
            
//            设置获取名字的相关属性
            attributeStr.addAttributes([NSForegroundColorAttributeName : UIColor.lightGrayColor(), NSFontAttributeName : UIFont.systemFontOfSize(12)] , range : range)
            label.attributedText = attributeStr
            
        } else {
            label.text = "发微博"
        }
//        尺寸应在设置用户名后解决
        label.sizeToFit()
        return label
    }()
//        右侧的按钮(发送按钮)
    private lazy var rightButton: UIButton = {
       let btn = UIButton()
//        添加点击事件
        btn.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
//        设置背景图片
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
         btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        
//        设置title
        btn.setTitle("发送", forState: .Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(15)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        btn.size = CGSize(width: 45, height: 30)
        //  因为button被UIBarButtonItem,这样设置没有作用
        //        button.enabled = false
        
        return btn
    }()
//     自定义的textView
    private lazy var textView: LSZComposeTextView = {
        let view = LSZComposeTextView()
        view.delegate = self
        view.placeHolder = "听说下雨天音乐跟辣条更配呦~"
        view.font = UIFont.systemFontOfSize(15)
//        垂直方向开启弹簧效果
        view.alwaysBounceVertical = true
        return view
    }()
//    自定义ToolBar
    private lazy var tooBar: LSZComposeToolBar = {
       let view = LSZComposeToolBar(frame: CGRectZero)
        return view
    }()
    
//    配图View
    private lazy var pictureView: LSZComposePictureView = {
       let view = LSZComposePictureView()
        return view
    }()
//    表情键盘View
    private lazy var keyBoard: LSZEmoticonKeyBoard = {
        let view = LSZEmoticonKeyBoard()
//        设置视图大小
        view.size = CGSize(width: self.textView.width, height: 216)
        return view
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setUpUI()
    }
    
    private func setUpUI() {
    //        监听键盘的改变
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        setUpNavUI()
        
        view.addSubview(textView)
        view.addSubview(tooBar)
        textView.addSubview(pictureView)
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(self.tooBar.snp_top)
        }
        
        tooBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.height.equalTo(30)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            make.leading.equalTo(textView).offset(10)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
        }
        
        
    
//        设置闭包
        tooBar.selectedToolBarButtonClose = { [weak self] (type: LSZComposeToolBarButtonType) in
            
            switch type {
            case .Picture:
                print("图片")
                self?.didSelectedPicture()
            case .Mention:
                print("@")
            case .Trend:
                print("话题")
            case .Emoticon:
                print("表情")
                self?.didSelectedEmoticon()
            case .Add:
                print("加号")
            }
            
        }
        
        pictureView.didSelectedAddClosure = { [weak self] in 
               self?.didSelectedPicture()
        }
        
    }
    
    private func setUpNavUI() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.titleView = titleLabel
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
//        设置为enabled状态
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
    // MARK: 监听键盘frame改变的事件
    @objc private func keyboardChangeFrame(noti: NSNotification){
        
//        获取键盘的frame
        let keyboardFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
//        获取键盘弹起的动画时长
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
//        更新约束
        tooBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - ScreenHeight)
        }

        
//        执行动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
//    顶部按钮的点击事件
    @objc private func cancelAction() {
//        取消第一响应者
        self.view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func sendAction() {
//        带图片微博上传接口
        if pictureView.images.count > 0 {
            let accessToken = LSZUserAccountViewModel.sharedUserAccount.accessToken!
            let image = pictureView.images.first!
            let text = textView.text!
            SVProgressHUD.show()
            
            LSZNetworkTools.sharedToos.upload(accessToken, status: text, image: image, callBack: { (response, error) -> () in
                if error != nil {
                    print(error)
                    SVProgressHUD.showErrorWithStatus("发送失败")
                    return
                }else {
                    //  发送成功
                    SVProgressHUD.showSuccessWithStatus("发送成功")
                }

            })
            
            
        } else {
            
            let accessToken = LSZUserAccountViewModel.sharedUserAccount.accessToken!
            let text = textView.text!
            
            SVProgressHUD.show()
            
            LSZNetworkTools.sharedToos.update(accessToken, status: text, callBack: { (response, error) -> () in
                
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("发送失败")
                    return
                }
                SVProgressHUD.showSuccessWithStatus("发送成功")
            })
            
        }
    }

    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
}

//处理toolbar按钮的点击逻辑
extension LSZComposeViewController: UIImagePickerControllerDelegate , UINavigationControllerDelegate{
//    表情键盘处理
    func didSelectedEmoticon() {
//        显示系统键盘或者表情键盘
        if textView.inputView == nil {
//            设置成自定义的键盘
            textView.inputView = keyBoard
//            设置键盘显示icon
            tooBar.showEmotionIcon(true)
        } else {
//                设置成系统键盘
            textView.inputView = nil
//            设置显示emoti的icon
            tooBar.showEmotionIcon(false)
        }
        
//        获取第一响应者
        textView.becomeFirstResponder()
//        重新刷新InputView
        textView.reloadInputViews()
    }
    
    
    
    
//    图片处理
    func didSelectedPicture() {
        let imagePictureCtr = UIImagePickerController()
//        设置代理
        imagePictureCtr.delegate = self
        
//        判断是否支持这个来源类型
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
//           表示支持相机
            imagePictureCtr.sourceType = .Camera
        } else {
//            表示不支持相机.使用图库
            imagePictureCtr.sourceType = .PhotoLibrary
        }
        
//        判断是否支持前置或者后置摄像头
        
        if UIImagePickerController.isCameraDeviceAvailable(.Front){
             print("支持前置摄像头")
        } else if UIImagePickerController.isCameraDeviceAvailable(.Rear){
            print("支持后置摄像头")
        } else {
            print("不支持摄像功能")
        }
//        允许用户编辑
//        imagePictureCtr.allowsEditing = true
        
        presentViewController(imagePictureCtr, animated: true, completion: nil)
    }
    
    
//    获取选中的图片 ,如果实现了协议就不会自己调用dismissViewControllerAnimated
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let scaleImage = image.scaleImageWithScaleWidth(200)
        pictureView.addImage(scaleImage)
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    
   
    
}





//实现UITextVieDelegate方法
extension LSZComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
//        根据文本内容判断发送按钮是否可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
//    当滚动的时候取消第一响应者
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    
    
    
}




